
#define MyAppName "圆通打印助手"
#define MyAppVersion "2.0.1"
#define MyAppPublisher "wms"
#define MyAppURL "http://ywmsw.yto.net.cn/"
#define MyAppExeName "打印助手.exe"

[Setup]
; 注: AppId的值为单独标识该应用程序。
; 不要为其他安装程序使用相同的AppId值。
; (若要生成新的 GUID，可在菜单中点击 "工具|生成 GUID"。)
AppId={{B9E4439E-0DFB-4DD8-86E4-99EC819C0A9C}}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName=D:\Program Files\YTO WMS Assistant
DisableProgramGroupPage=yes
OutputDir=E:\bundles
OutputBaseFilename=打印助手安装程序{#MyAppVersion}
SetupIconFile=D:\ideaWorkSpace\yto-print-assistant\src\main\resources\image\icon.ico
Compression=lzma
SolidCompression=yes
WizardStyle=modern
PrivilegesRequired=admin
; 启用安装日志记录，在与安装程序相同的目录中创建日志文件
SetupLogging=yes

 [Code]
const HKEY_SESSION_MANAGER = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';

function EnvAddPath(installPath: string): Boolean;
var
  paths: string;
  pathsUpper: string;
  list: TStringList;
begin
  Result := True;
  // 检索当前路径
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE, HKEY_SESSION_MANAGER, 'Path', paths) then
    paths := '';
  pathsUpper := Uppercase(paths);

  list := TStringList.Create;
  try
    list.Delimiter := ';';
    list.StrictDelimiter := True;
    list.DelimitedText := paths;
    // 如果路径中已经包含目标路径，则直接返回。
    if (Pos(';' + Uppercase(installPath) + ';',  ';' + pathsUpper + ';') > 0) or
       (Pos(';' + Uppercase(installPath) + '\\;', ';' + pathsUpper + ';') > 0) then
      Exit;

    if list.Count > 0 then
    begin
      if list[list.Count - 1] <> '' then
        list.Add(';');
    end;
    list.Add(installPath);

    if RegWriteStringValue(HKEY_LOCAL_MACHINE, HKEY_SESSION_MANAGER, 'Path', list.DelimitedText) then
      Log(Format('The [%s] added to PATH: [%s]', [installPath, list.DelimitedText]))
    else
    begin
      Result := False;
      Log(Format('Error while adding the [%s] to PATH: [%s]', [installPath, list.DelimitedText]));
    end;
  finally
    list.Free;
  end;
end;

function EnvRemovePath(instlPath: string): Boolean;
var
  paths: string;
  pathsUpper: string;
  instlPathUpper: string;
  P, DelimLen: Integer;
begin
  Result := True;
  // 如果注册表项不存在，则直接返回。
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE, HKEY_SESSION_MANAGER, 'Path', paths) then
    Exit;

  pathsUpper := Uppercase(paths);
  instlPathUpper := Uppercase(instlPath);

  P := Pos(';' + instlPathUpper + ';', ';' + pathsUpper + ';');
  if P = 0 then
  begin
    DelimLen := 2; // 可能以 '\\;' 结尾
    P := Pos(';' + instlPathUpper + '\\;', ';' + pathsUpper + ';');
    if P = 0 then
      Exit;
  end
  else begin
    DelimLen := 1;
  end;

  // 更新路径变量
  Delete(paths, P, Length(instlPath) + DelimLen);
  SetLength(paths, Length(paths));

  if RegWriteStringValue(HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'Path', paths) then
    Log(Format('The [%s] removed from PATH: [%s]', [instlPath, paths]))
  else begin
    Result := False;
    Log(Format('Error while removing the [%s] from PATH: [%s]', [instlPath, paths]));
  end;
end;

[Code]

procedure CreateBatFile;
    var
     BatFilePath: string;
     BatFileContent: string;
    begin
     BatFilePath := ExpandConstant('{app}\run_printer.bat');
     BatFileContent := '@echo off' + #13#10 +
                      'cd /d "' + ExpandConstant('{app}') + '"' + #13#10 +
                      'start "" ""{#MyAppExeName}"' + #13#10 +
                      'exit';
     SaveStringToFile(BatFilePath, BatFileContent, False);
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  LogFilePathName, NewFilePathName: string;
  ResultCode: Integer;
  AppDir: string;
begin
  // 获取默认日志文件的路径和名称
  LogFilePathName := ExpandConstant('{log}');
  // 获取新日志文件的保存路径和名称
  NewFilePathName := ExpandConstant('{app}\') + ExtractFileName(LogFilePathName);

  if CurStep = ssPostInstall then
      begin
        CreateBatFile;
      end;

  if CurStep = ssDone then
      begin
        // 将jre路径添加到系统环境变量中
        if not EnvAddPath(ExpandConstant('{app}\jre1.8\bin')) then
          MsgBox('Failed to add jre path to system environment variable.', mbError, MB_OK);

        // 在安装完成后将默认日志文件复制到新路径
        FileCopy(LogFilePathName, NewFilePathName, false);

        if IsTaskSelected('launchafterinstall') then
          begin
            AppDir := ExpandConstant('{app}');
            // 设置工作目录,在使用 ShellExec 函数时，runas 参数会导致程序以管理员权限运行，
            // 这可能会导致工作目录不正确。为了确保工作目录正确，此处在调用 ShellExec 之前显式设置工作目录
            SetCurrentDir(AppDir);
            ShellExec('runas', ExpandConstant('{app}\{#MyAppExeName}'), '', AppDir, 1, false, ResultCode);
          end;
      end;
end;

procedure DeinitializeUninstall();
    begin
      // 从系统环境变量中删除jre路径
      if not EnvRemovePath(ExpandConstant('{app}\jre1.8\bin')) then
        MsgBox('Failed to remove jre path from system environment variable.', mbError, MB_OK);
    end;

[Languages]
Name: "chinesesimp"; MessagesFile: "compiler:Default.isl"

[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: checkablealone;
Name: "launchafterinstall"; Description: "安装完成后立即启动{#MyAppName}"; GroupDescription: "安装后操作"; Flags: checkablealone

[Files]
Source: "D:\ideaWorkSpace\yto-print-assistant\target\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
Source: "C:\Program Files\Java\jre-1.8\*"; DestDir: "{app}\jre1.8"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "D:\ideaWorkSpace\yto-print-assistant\lib\*"; DestDir: "{app}\lib"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "D:\ideaWorkSpace\yto-print-assistant\db\*"; DestDir: "{app}\db"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "D:\ideaWorkSpace\yto-print-assistant\src\main\resources\image\icon.ico"; DestDir: "{app}"; Flags: ignoreversion


[Registry]
Root: HKLM; Subkey: "SOFTWARE\JavaSoft\Java Runtime Environment"; ValueType: string; ValueName: "CurrentVersion"; ValueData: "1.8.0_411"; Flags: uninsdeletevalue; Check: IsJavaRuntimeEnvironmentNotInstalled
Root: HKLM; Subkey: "SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_411"; ValueType: string; ValueName: "JavaHome"; ValueData: "{app}\jre1.8"; Flags: uninsdeletevalue; Check: IsJavaRuntimeEnvironmentNotInstalled
Root: HKLM; Subkey: "SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_411"; ValueType: string; ValueName: "MicroVersion"; ValueData: "0"; Flags: uninsdeletevalue; Check: IsJavaRuntimeEnvironmentNotInstalled
Root: HKLM; Subkey: "SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_411"; ValueType: string; ValueName: "RuntimeLib"; ValueData: "{app}\jre1.8\bin\server\jvm.dll"; Flags: uninsdeletevalue; Check: IsJavaRuntimeEnvironmentNotInstalled

Root: HKCR; Subkey: "ytoWMSAssistant"; ValueType: string; ValueName: ""; ValueData: "URL:ytoWMSAssistant Protocol"; Flags: uninsdeletekey
Root: HKCR; Subkey: "ytoWMSAssistant"; ValueType: string; ValueName: "URL Protocol"; ValueData: ""; Flags: uninsdeletevalue
Root: HKCR; Subkey: "ytoWMSAssistant\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\run_printer.bat,0"; Flags: uninsdeletevalue
Root: HKCR; Subkey: "ytoWMSAssistant\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\run_printer.bat"" ""%1"""; Flags: uninsdeletevalue



[Code]
function IsJavaRuntimeEnvironmentNotInstalled(): Boolean;
begin
  // Check if the Java Runtime Environment registry key exists
  Result := not RegKeyExists(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_411');
end;


[Icons]
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon; WorkingDir: "{app}"

[UninstallDelete]
; 删除安装目录中的所有文件和子目录
Type: filesandordirs; Name: "{app}\*"

[UninstallRun]
; 终止目标程序
Filename: "taskkill"; Parameters: "/F /IM javaw.exe /T /FI ""IMAGENAME eq javaw.exe"" /FI ""WINDOWTITLE eq 圆通打印助手*"""; StatusMsg: "正在终止 圆通打印助手进程 ..."; Flags: runhidden
; 删除安装目录本身（如果为空）
Filename: "{cmd}"; Parameters: "/C rmdir /S /Q ""{app}"""; StatusMsg: "Removing application directory..."


;[Run]
;Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent; WorkingDir: "{app}";

